package com.item1024.beans;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.github.pagehelper.Page;

import java.util.HashMap;
import java.util.Map;
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class ApiResult {

    public Object getPage() {
        return page;
    }

    public ApiResult setPage(Object page) {
        this.page = page;
        return this;
    }

    public static enum ApiResultCode{
        ERR_SYSTEM(301),
        ERR_AUTH(311),
        ERR_PARAM(321),
        ERR_OPERATION(331),
        ERR_HTTPREQ(341),
        ERR_DATABASE(351),
        SUCCESS(200);

        private int code;
        ApiResultCode(int code){
            this.code = code;
        }

        public int code(){
            return code;
        }
    }

    private int code;
    private String message;
    private Object data;
    private Object page;

    private ApiResult(){

    }


    public ApiResult(int code){
        this.code = code;
    }

    public ApiResult(int code , String messgae){
        this.code = code;
        this.message = messgae;
    }

    public static ApiResult getSuccessInstance(){
        return new ApiResult(ApiResultCode.SUCCESS.code());
    }

    public ApiResult data(Object data){
        this.data = data;

        if(data instanceof Page){
            this.page = parsePage((Page)data);
        }

        return this;
    }

    public static Map<String ,Object> parsePage(Page page){
        Map<String ,Object> pageMap = new HashMap<>();
        pageMap.put("page_num" , page.getPageNum());
        pageMap.put("pages" , page.getPages());
        pageMap.put("page_size" , page.getPageSize());
        pageMap.put("total" , page.getTotal());
        return pageMap;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "ApiResult{" +
                "code=" + code +
                ", message='" + message + '\'' +
                ", data=" + data +
                ", page=" + page +
                '}';
    }
}
